import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { ConfirmationService, SelectItem, TreeNode } from 'primeng/primeng';
import { MdlSnackbarService } from '@angular-mdl/core';
import { SystemInfoService } from './service/sysinfo.service';
import { switchMap } from 'rxjs/operators';
@Component({
  templateUrl: './sysinfo-detail.component.html',
  styleUrls: [ './sysinfo-detail.component.scss' ],
  providers: [ ConfirmationService ]
})
export class SysinfoDetailComponent implements OnInit {
  sysInfoForm: FormGroup;
  sysInfoIcons: string[] = new Array('mail', 'workflow', 'rabbit', 'call', 'carema', 'clock', 'download', 'film', 'find', 'mac', 'mail', 'map', 'music', 'note', 'pic', 'setting', 'upload', 'workflow', 'date', 'databank');
  frameTypes: any[] = [{label:'内部系统',value: 0},{label:'外链系统',value: 1}];
  sysInfo: any = { 'sysId': 0 };

  constructor(
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private sysInfoService: SystemInfoService,
    private mdlSnackbarService: MdlSnackbarService,
    private confirmationService: ConfirmationService,
  ) { }

  ngOnInit() {
    /** 解析URL，记录点击事件 */
    this.route.paramMap.pipe(
      switchMap((params: ParamMap) => this.sysInfoService.getSysInfoDetail(+params.get('id')))
    ).subscribe(sysInfo => {
        if(!sysInfo)return;
        this.sysInfo = sysInfo;
        this.buildForm();
      });
    this.buildForm();
  }

  /**点击更新或保存 */
  saveUpdateSysInfo($event) {
    this.sysInfoService.saveUpdateSysInfo(this.sysInfoForm.value)
      .subscribe(data => {
        this.sysInfoService.announceMission(data["id"]);
        this.mdlSnackbarService.showToast('数据保存成功！');
      }, error => {
        this.mdlSnackbarService.showToast('数据保存失败！');
      });
  }

  /**点击删除 */
  deleteSysInfo($event) {
    this.confirmationService.confirm({
      header: '确认',
      message: '您确定要删除该条记录吗？',
      accept: () => {
        this.sysInfoService.deleteSystem(this.sysInfo.sysId)
          .subscribe(data => {
            this.mdlSnackbarService.showToast('数据删除成功！');
            this.sysInfoService.announceMission("");
          }, error => {
            this.mdlSnackbarService.showToast('数据删除失败！');
          });
      }
    });
  }

  /**新增系统配置 */
  addSysInfo($event) {
    this.sysInfo = { 'sysId': -1, iconImage : "mail" };
    this.buildForm();
  }

  /**点击刷新 */
  refreshSysInfo($event) {
    this.sysInfoService.getSysInfoDetail(this.sysInfo.sysId)
      .subscribe(sysInfo => {
        this.sysInfo = sysInfo;
        this.buildForm();
        this.sysInfoService.announceMission(this.sysInfo.sysId + "");
        this.mdlSnackbarService.showToast('数据刷新成功！');
      });
  }

  buildForm(): void {
    this.sysInfoForm = this.fb.group({
      'sysId': [this.sysInfo.sysId],
      'iconCss': [this.sysInfo.iconCss],
      'iconImage': [this.sysInfo.iconImage],
      'sysName': [this.sysInfo.sysName, [
        Validators.required,
        Validators.minLength(4),
        Validators.maxLength(24)]
      ],
      'frameType': [this.sysInfo.frameType],
      'seniorId': [this.sysInfo.seniorId],
      'sysPath': [this.sysInfo.sysPath, [Validators.required]],
      'sysDesc': [this.sysInfo.sysDesc],
    });

    this.sysInfoForm.valueChanges
      .subscribe(data => this.onValueChanged(data));
    this.onValueChanged();
  }

  onValueChanged(data?: any) {
    if (!this.sysInfoForm) { return; }
    const form = this.sysInfoForm;

    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);

      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  formErrors = {
    'sysName': '',
    'sysPath': ''
  };


  validationMessages = {
    'sysName': {
      'required': '系统名称不能为空',
      'minlength': '系统名称长度不能少于4个字符',
      'maxlength': '系统名称长度不能超过20个字符'
    },
    'sysPath': {
      'required': '系统访问路劲不能为空'
    }
  };
  //数据更新按钮
    basisUpdate(){
        this.sysInfoService.basisUpdate().subscribe(data => {
            if (data) {
                this.mdlSnackbarService.showToast('数据刷新成功！');
            } else {
                this.mdlSnackbarService.showToast('数据刷新失败！');
            }
            });
    }
}
